package com.viphome.automic;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by wangzhanjin on 2018/3/26.
 * 不原子性存在的问题
 */
public class AtomicIntegerTest {

    /**
     * 1.可见性、序列性、不保证原子性
     */
    private static volatile int value = 0;
    private static Set<Integer> set = Collections.synchronizedSet(new HashSet<Integer>());

    public static void main(String[] args) throws Exception {
        Thread t1 = new Thread() {
            @Override
            public void run() {
                int x = 0;
                while (x < 500) {
                    set.add(value);
                    int tmp = value;
                    System.out.println(Thread.currentThread().getName() + "：" + tmp);
                    value += 1;
                    x++;
                    /**
                     * value = value+1；
                     * （1）value从主存里拿到值
                     * （2）执行累加器 add 1 => x
                     * （3） assign the value to x
                     * （4）flush to main memory
                     */
                    //拿过来是0，执行+1操作，可是操作的时候可能直接是1了
                    //中间会有步骤直接跳过
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                int x = 0;
                while (x < 500) {
                    set.add(value);
                    int tmp = value;
                    System.out.println(Thread.currentThread().getName() + "：:" + tmp);
                    value += 1;
                    x++;
                }
            }
        };
        Thread t3 = new Thread() {
            @Override
            public void run() {
                int x = 0;
                while (x < 500) {
                    set.add(value);
                    int tmp = value;
                    System.out.println(Thread.currentThread().getName() + "：::" + tmp);
                    value += 1;
                    x++;
                }
            }
        };

        t1.start();
        t2.start();
        t3.start();
        t1.join();
        t2.join();
        t3.join();

        //这个样打印应该是1500才对
        System.out.println(set.size());


    }
}
